const Router = require("koa-router");
const fs = require("fs");
const path = require("path");
const send = require("koa-send");
const List = require("../models/list.js");
const Category = require("../models/category.js");
const Presets = require("../models/presets.js");

const homeRouter = new Router({
  prefix: "/dream",
});

homeRouter.get("/presets", async (ctx, next) => {
  const presets = await Presets.find();
  ctx.body = presets[0];
});

homeRouter.get("/category", async (ctx, next) => {
  const categories = await Category.find({}, { "category": 1 });
  ctx.body = categories;
});

homeRouter.get("/category/types", async (ctx, next) => {
  const typeId = ctx.query.typeId;
  console.log(typeId,'typeId');
  
  const categoryTypes = await Category.find({ "_id": typeId });
  ctx.body = categoryTypes;
});

homeRouter.get("/list", async (ctx, next) => {
  console.log(ctx.query, 'ctx');

  const keyword = ctx.query.keyword;
  const current = Number(ctx.query.current) - 1
  const count = await List.countDocuments({ "name": new RegExp(keyword, "i") })
  const list = await List.find({ "name": new RegExp(keyword, "i") }).limit(10).skip(current * 10);
  ctx.body = {
    list,
    count
  };
});

homeRouter.get("/string", async (ctx, next) => {
  ctx.body = "koa2 string";
});

homeRouter.get("/json", async (ctx, next) => {
  ctx.body = {
    title: "koa2 json",
  };
});

// 下载文件
homeRouter.get("/download/:filename", async (ctx, next) => {
  let filename = ctx.params.filename;
  let filePath = `./static/download/${filename}`;
  // mime type, active the download window in browser
  ctx.attachment(filePath);
  await send(ctx, filePath);
  console.log("download successfully."); 
});

// 上传文件
function saveFile(file) {
  const reader = fs.createReadStream(file.path);
  let filePath = path.join(__dirname, "/static/upload/") + `/${file.name}`;
  const upStream = fs.createWriteStream(filePath);
  reader.pipe(upStream);
}

homeRouter.post("/upload", async (ctx, next) => {
  // console.log(ctx.request.files);
  const files = ctx.request.files.file;
  if (files.length > 1) {
    for (let file of files) {
      saveFile(file);
    }
  } else if (files) {
    saveFile(files);
  }
  ctx.body = "Upload successfully.";
});

module.exports = homeRouter
